/**
 * Created by cchen on 2015/5/14.
 */
'use strict';
angular.module('backofficeApp.communityRewardRule.controller', []).
    controller('communityRewardRuleCtrl', ['$scope', '$http', 'communityRewardRuleService', function ($scope , $http, communityRewardRuleService) {
        $scope.$watch('$viewContentLoaded', function () {
            $scope.rule_list = []
            $scope.filter = "all";
            btnCtrl(false, false, false);
            listRewardRules({filter: 'all'});
            $scope.reward_sources = [
                {name: 'v认证', value: 1}, {name: '推荐用户', value: 2}
            ];

            $scope.dateFrom = datePicker('#startDate');
            $scope.dateTo = datePicker('#endDate');
            $scope.comChange = true;


            function btnCtrl(isAdd, isUpdate, isDelete) {
                $scope.addBtnShow = isAdd;
                $scope.updateBtnShow = isUpdate;
                $scope.deleteBtnShow = isDelete;
            }

            function communityModel(isShow) {
                if (isShow) {
                    $('#community_model').modal('show');
                }
                else {
                    $('#community_model').modal('hide');
                }
            }

            function initDialog(data, showDialog, btnFlag) {
                var f = [[true, false, false], [false, true, false], [false, false, true]]
                btnCtrl(f[btnFlag][0], f[btnFlag][1], f[btnFlag][2]);
                communityModel(showDialog);
                $scope.crule = data;
                $scope.onErrorMsg = "";
                $scope.showErrorMsg = false;
            }


            function datePicker(id) {
                function d(id) {
                    var self = this;
                    $(id).datepicker({
                        format: 'yyyy-mm-dd',
                        autoclose: true,
                        forceParse: false
                    }).on('changeDate', function (e) {
                        self.date = e.date;
                    }).on('show', function (e) {
                        $(".datepicker.datepicker-dropdown.dropdown-menu").css("z-index", "10000");

                    });

                }

                d.prototype.getValue = function (isFrom) {
                    if (isFrom) {
                        return this.date.setHours(0, 0, 0, 0)
                    }
                    return this.date.setHours(23, 59, 59, 0)
                }
                var date = new d(id);
                return date;
            }


            $scope.onErrorMsg = ""
            $scope.showErrorMsg = false;

            function notValidateDate(valueA, valueB) {
                if (!valueA || !valueB) {
                    return true
                }
                if (valueA >= valueB) {
                    return true;
                } else {
                    return false;
                }
            }

            function validateRule(rule) {
                if ($("#selCommunitys option").length <= 0) {//rule.community_id
                    $scope.onErrorMsg = "小区选择错误";
                    $scope.showErrorMsg = true;
                    return false;

                } else if (!rule.reward_expiredate_length && $scope.is_voucher_type === 1) {
                    $scope.onErrorMsg = "有效期错误";
                    $scope.showErrorMsg = true;
                    return false;
                }
                else if (!rule.reward_source) {
                    $scope.onErrorMsg = "奖励选择错误";
                    $scope.showErrorMsg = true;
                    return false;
                }
                else if (!rule.voucher_type_id) {
                    $scope.onErrorMsg = "奖励类型错误"
                    $scope.showErrorMsg = true;
                    return false;
                } else if (notValidateDate(rule.from_time, rule.to_time)) {
                    rule.from_time = new Date(rule.from_time).Format('yyyy-MM-dd');
                    rule.to_time = new Date(rule.to_time).Format('yyyy-MM-dd');
                    $scope.onErrorMsg = "活动开始或结束日期选择错误"
                    $scope.showErrorMsg = true;
                    return false;
                }
                return true;
            }

            function listRewardRules(filter) {
                communityRewardRuleService.list.get(filter, function (res) {
                    $scope.rule_list = res.data;
                    $scope.filter = filter.filter;
                    $scope.ck = false;
                })
            }

            communityRewardRuleService.commList.get(function (res) {
                $scope.commList = res.data;
                //console.log($scope.commList);
            });
            communityRewardRuleService.typeList.get(function (res) {
                $scope.typeList = res.data;
            });

            $scope.changeVoucherType = function (type_id) {
                $scope.typeList.forEach(function (item) {
                    if (item.id + "" === type_id) {
                        $scope.is_voucher_type = item.type
                    }
                })
            }

            $scope.setCommunityName = function () {
                var communityName = $("#community_menu").find("option:selected").html();
                $scope.crule.community_name = communityName.replace(/\s/g, '');

            }

            $scope.newDialog = function () {
                $scope.comChange = true;
                $("#selCommunitys option").appendTo($("#communitys"));
                initDialog({}, true, 0);
                $scope.is_voucher_type = 1;
            };

            $scope.updateDialog = function (rule) {
                $scope.comChange = false;
                $("#selCommunitys option").appendTo($("#communitys"));
                $("#communitys option[value="+rule.community_id+"]").appendTo($("#selCommunitys"));
                $scope.dateFrom = datePicker('#startDate');
                $scope.dateTo = datePicker('#endDate');
                $scope.changeVoucherType(rule.voucher_type_id);
                initDialog(rule, true, 1)
            }

            $scope.deleteDialog = function (rule) {
                $scope.changeVoucherType(rule.voucher_type_id);
                initDialog(rule, true, 2);
            };

            $scope.findCommunities = function (communityName) {

                if (communityName && communityName.length === 0) {
                    listRewardRules({filter: 'all'});
                } else {

                    listRewardRules({filter: communityName});
                }
            }

            function noConflicts(newRule){
                var flag = true;
                $scope.rule_list.forEach(function(rule){
                    if(newRule.community_id == rule.community_id && newRule.reward_source == rule.reward_source){
                        if(!(new Date(newRule.to_time).Format('yyyy-MM-dd') < rule.from_time || new Date(newRule.from_time).Format('yyyy-MM-dd') > rule.to_time)){
                            if(newRule.objId != rule.objId){
                                flag = false;
                            }
                        }
                    }
                });
                return flag;
            }


            $scope.add = function (rule) {
                var startDate = $('#startDate').val();
                var endDate = $('#endDate').val();
                rule.from_time = $scope.dateFrom.getValue(true);
                rule.to_time = $scope.dateTo.getValue(false);
                rule.communityName = $scope.communityName ? $scope.communityName : rule.communityName;
                if (!validateRule(rule)) {
                    rule.from_time = startDate;
                    rule.to_time = endDate;
                    return;
                }
                if(!noConflicts(rule)){
                    rule.from_time = startDate;
                    rule.to_time = endDate;
                    $scope.onErrorMsg="时间范围选择冲突!";
                    $scope.showErrorMsg=true;
                    return;
                }
                var communityLength = 0,
                    communityRewardRuleSave = function(){
                        rule.community_id = $("#selCommunitys option")[communityLength].value;
                        rule.community_name = $("#selCommunitys option")[communityLength].label;
                        communityRewardRuleService.obj.save(rule,function (res, arg1, arg2) {
                            if (res.result.status == 0) {
                                rule.from_time = new Date(rule.from_time).Format('yyyy-MM-dd');
                                rule.to_time = new Date(rule.to_time).Format('yyyy-MM-dd');
                                $scope.onErrorMsg = res.result.message;
                                $scope.showErrorMsg = true;
                            } else {
                                communityModel(false);
                                listRewardRules({filter: $scope.filter});
                            }
                            communityLength++;
                            if(communityLength == $("#selCommunitys option").length)return;
                            communityRewardRuleSave();
                        });
                    };
                communityRewardRuleSave();
                //for(var i = 0;i < $("#selCommunitys option").length;i++){
                //    rule.community_id = $("#selCommunitys option")[i].value;
                //    rule.community_name = $("#selCommunitys option")[i].label;
                //    communityRewardRuleService.obj.save(rule,function (res, arg1, arg2) {
                //        if (res.result.status == 0) {
                //            rule.from_time = new Date(rule.from_time).Format('yyyy-MM-dd');
                //            rule.to_time = new Date(rule.to_time).Format('yyyy-MM-dd');
                //            $scope.onErrorMsg = res.result.message;
                //            $scope.showErrorMsg = true;
                //        } else {
                //            communityModel(false);
                //            listRewardRules({filter: $scope.filter});
                //        }
                //    });
                //}
            };

            $scope.update = function (rule) {
                var startDate = $('#startDate').val();
                var endDate = $('#endDate').val();
                var start = new Date(Date.parse(startDate));
                var end = new Date(Date.parse(endDate));
                start.setHours(0, 0, 0, 0);
                end.setHours(23, 59, 59, 0);
                rule.from_time = start.getTime();
                rule.to_time = end.getTime();
                if (!validateRule(rule)) {
                    rule.from_time = startDate;
                    rule.to_time = endDate;
                    return;
                }
                if(!noConflicts(rule)){
                    rule.from_time = startDate;
                    rule.to_time = endDate;
                    $scope.onErrorMsg="时间范围选择冲突!";
                    $scope.showErrorMsg=true;
                    return;
                }
                communityRewardRuleService.obj.update(rule, function (res, arg1, arg2) {
                    listRewardRules({filter: $scope.filter});
                });
                communityModel(false);

            }
            $scope.delete = function (rule) {
                if (!validateRule(rule)) {
                    return;
                }
                communityRewardRuleService.obj.delete(rule, function (res, arg1, arg2) {
                    listRewardRules({filter: $scope.filter});
                });
                communityModel(false);
            }

            //全部移到右边
            $scope.addAllCommunity = function () {
                //获取全部的选项,删除并追加给对方
                $('#communitys option').appendTo('#selCommunitys');
            };

            //全部移到左边
            $scope.removeAllCommunity = function () {
                $('#selCommunitys option').appendTo('#communitys');
            };
            $scope.addCommunity = function () {
                //先判断是否有选中
                if (!$("#communitys option").is(":selected")) {
                    alert("请选择需要移动的选项")
                }
                //获取选中的选项，删除并追加给对方
                else {
                    $('#communitys option:selected').appendTo('#selCommunitys');
                }
            };

            //移到左边
            $scope.removeCommunity = function () {
                //先判断是否有选中
                if (!$("#selCommunitys option").is(":selected")) {
                    alert("请选择需要移动的选项")
                }
                else {
                    $('#selCommunitys option:selected').appendTo('#communitys');
                }
            };

            $scope.cnameFilter = function(name){
                var html = "";
                $scope.commList.forEach(function(item){
                    if(item.communityName.match(name)){
                        html += "<option value="+item.objId+">"+item.communityName+"</option>";
                    }
                    $("#communitys").html(html);
                    if(name == "")$("#selCommunitys").html("");
                });
            };

            $(document).on("dblclick","#communitys option",function(){
                $(this).appendTo('#selCommunitys');
            });
            $(document).on("dblclick","#selCommunitys option",function(){
                $(this).appendTo('#communitys');
            });

            $scope.allCheck = function (ck,openType) {

                if (!ck) {
                    $scope.rules = [];

                    $("[name = chkItem]:checkbox").prop("checked", true);
                    $scope.rule_list.forEach(function (banner) {
                        $scope.rules.push(banner)
                    })
                } else {
                    $scope.rules = [];

                    $("[name = chkItem]:checkbox").prop("checked", false);
                    $scope.rule_list.forEach(function (banner) {
                        $scope.rules.remove(banner);
                    })
                };
                //console.debug($scope.questions);
            };

            $scope.checkChange = function(ckc){
                if($scope.ck){
                    $scope.ck = false;
                };
            };

            $scope.rules = new Array();
            $scope.ruleToggle = function (rule) {

                var isexist = false;
                $scope.rules.forEach(function (item) {
                    if(item.objId == rule.objId){
                        isexist = true;
                    };
                });
                if(isexist){
                    $scope.rules.remove(rule);
                }else{
                    $scope.rules.push(rule);
                };
                console.info($scope.rules)
            };

            $scope.editTimeDialog = function () {
                if($scope.rules== null || $scope.rules.length==0){
                    alert("请选择需要编辑的奖励机制!");
                    return;
                }
                $scope.dateFrom = datePicker('#startDate2');
                $scope.dateTo = datePicker('#endDate2');
                $('#setRuleTime_model').modal('show');
            };

            $scope.saveTime = function (){

                var startDate = $('#startDate2').val();
                var endDate = $('#endDate2').val();
                var start = new Date(Date.parse(startDate));
                var end = new Date(Date.parse(endDate));
                end.setHours(23, 59, 59, 0);
                var rules = [];
                $scope.rules.forEach(function(rule){
                    rules.push({
                            id: rule.objId,
                            from_time: start.getTime(),
                            to_time: end.getTime()
                        });
                });
                var opt = {
                    rules : rules
                };

                $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/voucher/setRewardRule',opt, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $scope.findCommunities($scope.filter);
                    $('#setRuleTime_model').modal('hide');

                }).error(function () {
                });
            };


            $scope.deleteRule = function () {
                bootbox.confirm('是否确定删除?', function (result) {
                    var rules = [];
                    if (result) {
                        $scope.rules.forEach(function(rule){
                            rules.push({
                                    id: rule.objId
                                });
                        });
                        var opt = {
                            rules : rules
                        };

                        $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/voucher/deleteChkRewardRule',opt, {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (data) {
                            $scope.findCommunities($scope.filter);
                            $('#setRuleTime_model').modal('hide');
                        }).error(function () {
                        });
                    }
                }).find("div.modal-dialog").css({width: '30%'});
            };



        });
    }]);


angular.module('backofficeApp.communityRewardRule.services', ['ngResource']).
    factory('communityRewardRuleService', function ($resource) {
        return {
            obj: $resource('http://' + backOfficeHost + '/rest/v1.0/backoffice/voucher/rewardRule', {}, {
                'update': {method: 'PUT'},
                'delete': {method: 'DELETE'}
            }),
            list: $resource('http://' + backOfficeHost + '/rest/v1.0/backoffice/voucher/rewardRule/list/:filter', {}, {}),
            commList: $resource('http://' + backOfficeHost + '/rest/v1.0/communities/getAllCommunity', {}, {}),
            typeList: $resource('http://' + backOfficeHost + '/rest/v1.0/backoffice/voucher/rewardRule/type/list', {}, {})
        }
    })


Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}